package xps.and.uudaijia.userclient.view.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.bumptech.glide.Glide;
import com.jude.utils.JUtils;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscriber;
import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.data.baen.CodeBean;
import xps.and.uudaijia.userclient.data.baen.MapBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.service.RemoteService;
import xps.and.uudaijia.userclient.util.AppCommond;
import xps.and.uudaijia.userclient.util.CommonUtils;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.util.TtsUtil;
import xps.and.uudaijia.userclient.view.base.BaseActivity;
import xps.and.uudaijia.userclient.view.fragment.MapFragment;

public class MapViewActivity extends BaseActivity implements MapFragment.PinActivationListener, Handler.Callback {
    //地图页
    MapFragment mapViewFragment = new MapFragment();
    //到达预约地
    public String userid, OrderId = "", beginLng;
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.v_gap_line)
    View vGapLine;
    @BindView(R.id.actionbar_al)
    AutoRelativeLayout actionbarAl;
    @BindView(R.id.TX_ImageView)
    ImageView TXImageView;
    @BindView(R.id.name_TextView)
    TextView nameTextView;
    @BindView(R.id.dianhua_img)
    ImageView dianhuaImg;
    @BindView(R.id.ok_TextView)
    TextView okTextView;
    @BindView(R.id.end_TextView)
    TextView endTextView;
    @BindView(R.id.yincang)
    AutoLinearLayout yincang;
    private MyReceiver receiver = null;
    String startLng;
    String startLat;
    String endLngStr;
    String endLatStr;
    private Timer timer;
    private static int time = 10;
    protected static final int MSG_WHAT = 0;
    String userPhone;
    int radius = 1000;
    public int cishu = 1;

    String orderType;

    @Override
    protected int getLayout() {
        return R.layout.activity_mapview;
    }

    @Override
    protected void setData() {
        mapViewFragment.setPinVisibility(View.GONE);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
            LatLng latLng = new LatLng(globalPositionInfo.bdLocation.getLatitude(), globalPositionInfo.bdLocation.getLongitude());
            mapViewFragment.locat_startPoint(latLng);
            Intent intent = getIntent();
            startLng = intent.getStringExtra("startLng");
            startLat = intent.getStringExtra("startLat");
            orderType = intent.getStringExtra("orderType");

            if (!TextUtils.isEmpty(startLng) && !TextUtils.isEmpty(startLng)) {
                LatLng locat_endPoint = new LatLng(Double.parseDouble(startLat), Double.parseDouble(startLng));
                mapViewFragment.addMarker(locat_endPoint, R.drawable.s_s);
                mapViewFragment.moveCameraTo(locat_endPoint);
                UserNetWorks.getMapJingWeiDu(startLat + "", startLng + "", orderType, new Subscriber<MapBean>() {
                            @Override
                            public void onCompleted() {
                                Log.e("getMapJingWeiDu", "onCompleted");
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(MapBean mapBean) {
                                if (mapBean.getReturn_code().equals("SUCCESS")) {
                                    if (mapBean.getReturn_body() != null && mapBean.getReturn_body().size() > 0) {
                                        placeMarker(mapBean);
                                    }
                                } else if (mapBean.getReturn_code().equals("FAIL")) {
                                    JUtils.Toast(mapBean.getReturn_msg());
                                }
                            }
                        }
                );
            }

            endLngStr = intent.getStringExtra("endLngStr");
            endLatStr = intent.getStringExtra("endLatStr");
            if (!TextUtils.isEmpty(endLngStr) && !TextUtils.isEmpty(endLatStr)) {
                LatLng locat_endPoint = new LatLng(Double.parseDouble(endLatStr), Double.parseDouble(endLngStr));
                mapViewFragment.addMarker(locat_endPoint, R.drawable.s_e);
            }
        }
    };

    void placeMarker(MapBean mapBean) {
        for (int i = 0; i < mapBean.getReturn_body().size(); i++) {
            MapBean.ReturnBodyBean reb = mapBean.getReturn_body().get(i);
            Log.e("getMapJingWeiDu", reb.toString());
            MapBean.ReturnBodyBean.LatestLocationBean latestLocationBean = reb.getLatest_location();
            LatLng locat_endPointA = new LatLng(latestLocationBean.getLatitude(), latestLocationBean.getLongitude());
            mapViewFragment.addBQXMarker(locat_endPointA, reb.getEntity_desc().toString());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.equals(getClass().getSimpleName())) {
                unreg();
                finish();
                break;
            }
        }
    }

    void unreg() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);

        Intent intent = getIntent();
        userid = intent.getStringExtra("userId");
        OrderId = intent.getStringExtra("orderId");
        startLng = intent.getStringExtra("startLng");
        startLat = intent.getStringExtra("startLat");
        endLngStr = intent.getStringExtra("endLngStr");
        endLatStr = intent.getStringExtra("endLatStr");
        mapViewFragment.setPinActionListener(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        CommonUtils.replaceFragment(R.id.container, mapViewFragment, getSupportFragmentManager());
        WebSocket();
        mHandler.sendEmptyMessageDelayed(0, 500);
        receiver = new MyReceiver();

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                TimemHandler.sendEmptyMessage(MSG_WHAT);
            }
        }, 0, 1000);
        yincang.setVisibility(View.GONE);
        IntentFilter filter = new IntentFilter();
        filter.addAction("xps.and.uudaijia.userclient.service.RemoteService");
        registerReceiver(receiver, filter);
    }

    @Override
    public void onPinMoved(final ArrayList<PoiInfo> p) {
        if (p == null || p.size() <= 0) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    @Override
    public void onPinMoveStart() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    void WebSocket() {
        Intent intent = new Intent(MapViewActivity.this, RemoteService.class);
        intent.putExtra("userId", userid);
        MapViewActivity.this.startService(intent);
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_tv_title, R.id.dianhua_img, R.id.iv_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                break;
            case R.id.actionbar_tv_title:
                break;
            case R.id.dianhua_img:
                Intent phoneIntent = new Intent("android.intent.action.CALL",
                        Uri.parse("tel:" + userPhone));
                //启动
                startActivity(phoneIntent);
                break;
            case R.id.iv_msg:
                PopupMenu popupMenu = new PopupMenu(MapViewActivity.this, view);
                popupMenu.getMenuInflater().inflate(R.menu.activity_main_drawer, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        int id = item.getItemId();
                        if (id == R.id.addfriend) {
                            Intent intent = new Intent(MapViewActivity.this, CancelActivity_v2.class);
                            intent.putExtra("panduan", "2");
                            intent.putExtra("orderID", OrderId);
                            startActivity(intent);
                        } else if (id == R.id.sao) {
                            showCYCDialogDH();
                        }
                        return true;
                    }
                });
                popupMenu.show();
                break;
        }
    }

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String count = bundle.getString("count");
            System.out.println("asdasdasdas" + count);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(count);
                if (jsonObject.getString("pushType").equals("scramble-order")) {
                    yincang.setVisibility(View.VISIBLE);
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    JUtils.Toast(jsonObject.getString("driverName") + "已接单");
                    nameTextView.setText(jsonObject.getString("driverName"));
                    okTextView.setText(jsonObject.getString("startAddress"));
                    endTextView.setText(jsonObject.getString("endAddress"));
                    userPhone = jsonObject.getString("driverPhone");
                    actionbarTvTitle.setText("已接单");
                    Glide.with(MapViewActivity.this).load(jsonObject.getString("driverHeadImg"))
                            .placeholder(R.mipmap.logo)
                            .bitmapTransform(new CropCircleTransformation(MapViewActivity.this))
                            .into(TXImageView);
                    ivMsg.setVisibility(View.GONE);
                    mapViewFragment.resetOverlay();
                    if (!TextUtils.isEmpty(startLng) && !TextUtils.isEmpty(startLat)) {
                        LatLng locat_endPoint = new LatLng(Double.parseDouble(startLat), Double.parseDouble(startLng));
                        mapViewFragment.addMarker(locat_endPoint, R.drawable.s_s);
                    }
                    if (!TextUtils.isEmpty(endLngStr) && !TextUtils.isEmpty(endLatStr)) {
                        LatLng locat_endPoint = new LatLng(Double.parseDouble(endLatStr), Double.parseDouble(endLngStr));
                        mapViewFragment.addMarker(locat_endPoint, R.drawable.s_e);
                    }
                } else if (jsonObject.getString("pushType").equals("BOD")) {
                    JUtils.Toast(jsonObject.getString("pushMsg") + "");
                    TtsUtil.getInstance().startSpeaking(jsonObject.getString("pushMsg") + "");
                } else if (jsonObject.getString("pushType").equals("arrival-to-destination")) {
                    yincang.setVisibility(View.VISIBLE);
                    actionbarTvTitle.setText("司机到达预约地");
                    JUtils.Toast("到达预约地");
                    ivMsg.setVisibility(View.GONE);
                } else if (jsonObject.getString("pushType").equals("start-off")) {
                    yincang.setVisibility(View.VISIBLE);
                    JUtils.Toast("司机正在执行订单");
                    actionbarTvTitle.setText("正在行驶");
                    ivMsg.setVisibility(View.GONE);
                } else if (jsonObject.getString("pushType").equals("confirm-cost")) {
                    yincang.setVisibility(View.VISIBLE);
                    MapViewActivity.this.finish();
                    Intent intent1 = new Intent(MapViewActivity.this, PaymentActivity.class);
                    intent1.putExtra("orderID", OrderId);
                    intent1.putExtra("driverName", jsonObject.getString("driverName"));
                    intent1.putExtra("driverHeadImg", jsonObject.getString("driverHeadImg"));
                    intent1.putExtra("liebia", "1");
                    finish();
                    startActivity(intent1);
                } else if (jsonObject.getString("pushType").equals("cancel-order")) {
                    finish();
                } else if (jsonObject.getString("pushType").equals("settlement-express-train-order")) {
                    Intent DaiJiaIntent = new Intent(MapViewActivity.this, DaiJiaPayMentActivity.class);
                    DaiJiaIntent.putExtra("orderID", jsonObject.getString("orderId"));
                    DaiJiaIntent.putExtra("driverHeadImg", jsonObject.getString("driverHeadImg"));
                    DaiJiaIntent.putExtra("driverName", jsonObject.getString("driverName"));
                    finish();
                    startActivity(DaiJiaIntent);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        TimemHandler.removeCallbacksAndMessages(null);
        TimemHandler=null;
        mHandler.removeCallbacksAndMessages(null);
        mHandler=null;
        unreg();
    }

    void getReminder() {
        UserNetWorks.getReminder(OrderId, String.valueOf(radius), new Subscriber<CodeBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(CodeBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast("催单成功");
                   /* showCYCDialog();*/
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                }
            }
        });
    }

    private Handler TimemHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_WHAT:
                    if (time > 0) {
                        time--;
                        Log.e("time", time + "");
                    } else {
                        showCustomizeDialog();
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                            time = 10;
                            cishu++;
                            Log.e("time", time + "");
                            radius = radius + 1000;
                            if (cishu <= 5) {
                                timer = new Timer();
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        TimemHandler.sendEmptyMessage(MSG_WHAT);
                                    }
                                }, 0, 1000);
                            }
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    };

    public void showCustomizeDialog() {
        getReminder();
    }

    public void showCYCDialogDH() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MapViewActivity.this);
        final View dialogView = LayoutInflater.from(MapViewActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("022-58397002");
        customizeDialog.setTitle("客服电话");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent phoneIntent = new Intent("android.intent.action.CALL",
                                Uri.parse("tel: 022-58397002"));
                        startActivity(phoneIntent);
                    }
                });
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }
}